package InterviewPractise;


import org.omg.CosNaming.NamingContextExtPackage.StringNameHelper;

import java.util.Arrays;
import java.util.Stack;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class ReverseWords {
    public static void main(String[] args){
        String words = "aa bb    cc  dd   ";
        ReverseWords reverseWords = new ReverseWords();
        reverseWords.print(reverseWords.reverseByMatcher(words));
        reverseWords.print(reverseWords.reverseBySpliter(words));
    }
    public void print(String[] strings){
        for(String str : strings){
            System.out.println(str + " ");
        }
    }

    public String[] reverseBySpliter(String words){
        String[] strings ;
        strings = words.trim().split("\\s{1,}");
        Stack stack = new Stack();
        for(String string:strings){
            stack.push(string);
        }
        String[] result = new String[strings.length];
        stack.copyInto(result);
        return result;
    }

    public String[] reverseByMatcher(String words){
        Pattern pattern = Pattern.compile("^\\s{0,}(\\w+)\\s{1,}");
        Matcher matcher = pattern.matcher(words);
        String[] strings = new String[matcher.groupCount()];
        while(matcher.find()){
            for(int i = 1;i <= matcher.groupCount();i++){
                strings[(i-1)] = matcher.group(matcher.groupCount()-(i-1));
            }
        }
        return strings;
    }
}
